axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'
const list = document.querySelector('#tb')
const form = document.querySelector('#bookForm')
const btn = document.querySelector('#btnAdd')
const btnSelect = document.querySelector('#btnSelect');
function renderData() {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
    list.innerHTML = data
      .map((item) => {
        return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="javascript:;" class="del" data-id='${item.id}'>删除</a></td>
    </tr>`
      })
      .join('')
  })
}
renderData()
form.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(this, { hash: true })
  axios.post('/api/addbook', data).then(({ data: res }) => {
    alert(res.msg)
    if (res.status !== 201) return
    this.reset()
    renderData()
  })
})
list.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    let delid = e.target.dataset.id
    console.log(typeof delid)
    axios.get(`/api/delbook?id=${delid}`).then(({ data: res }) => {
      renderData()
    })
  }
})
btnSelect.addEventListener('click', function () {
  const data = serialize(form, { hash: true })
  axios
    .get('/api/getbooks', { params: data })
    .then(({ data: { data: res } }) => {
      list.innerHTML = res
        .map((item) => {
          return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="javascript:;" class="del" data-id='${item.id}'>删除</a></td>
    </tr>`
        })
        .join('')
    })
})
